package com.wva.common.aspect;

import com.wva.common.annotation.authority.Open;
import com.wva.common.context.UserContext;
import com.wva.common.exception.BusinessException;
import com.wva.common.status.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 处理不需要登录的接口
 */
@Component
@Aspect
@Slf4j
@Order(-1000)
public class CheckLoginAspect {
    /**
     * 代理所有控制层方法的切入点
     */
    @Pointcut("execution(* com.wva.*.controller.*.*(..))")
    public void pt() {}

    /**
     * 控制层方法环绕通知
     */
    @Before("pt()")
    public void before(JoinPoint joinPoint) {
        //已经登录可以直接放行
        if(UserContext.isLogin()) return;

        //控制器有此注解直接放行
        if (joinPoint.getTarget().getClass().getAnnotation(Open.class) != null) {
            return;
        }

        //接口没有拒绝访问
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        if (method.getAnnotation(Open.class) == null) {
            //拦截请求
            throw new BusinessException(StatusEnum.UNAUTHORIZED);
        }
    }
}